/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-21，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.common;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.chinamobile.ln.ictenterprises.http.HttpAsyncTask;

import android.os.Handler;

public class Controller
{
    private static Controller _controller = null;
    private Handler _controlHandler = null;
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAXIMUM_POOL_SIZE = 15;
    private static final int KEEP_ALIVE = 5;
    private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(
        MAXIMUM_POOL_SIZE);
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r)
        {
            int count = mCount.getAndIncrement();
            return new Thread(r, count + "_thread");
        }
    };
    private static RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(
        CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS,
        sWorkQueue, sThreadFactory, rejectedExecutionHandler);

    public static Controller getInstance()
    {
        if (_controller == null)
        {
            _controller = new Controller();
        }
        return _controller;
    }

  
    /**
     * 执行一个 RUN 任务
     * 
     * @param httpThreadTask
     */
    public synchronized void execute(HttpAsyncTask httpThreadTask)
    {
        if (httpThreadTask != null)
        {
            if (httpThreadTask._cacheType == HttpAsyncTask.CACHE_TYPE_SAVE)
            {
                boolean flag = httpThreadTask.onPreExecuteCheckCache();
                if (flag)
                {
                    httpThreadTask.isNotifyUI = false;
                }
            }
            if (httpThreadTask.isNeedUpadteCache)
            {
                sExecutor.execute(httpThreadTask);
            }
        }
    }

    public Handler getControlHandler()
    {
        if (_controlHandler != null)
        {
            return _controlHandler;
        }
        return null;
    }
}
